package za.co.smartmi.interceptor;

import org.aopalliance.intercept.MethodInvocation;
/**
 * Abstract class for interceptors that catch exceptions and log (or translate) them.
 */
public abstract class AbstractExceptionTranslatingInterceptor {
    public AbstractExceptionTranslatingInterceptor() {
        super();
    }

    protected String buildMessage(MethodInvocation methodInvocation, Throwable ex) {
        return buildMessage(methodInvocation, ex, getRootCause(ex));
    }

    protected String buildShortMessage(Throwable ex) {
        return getRootCause(ex).getMessage();
    }

    private String buildMessage(MethodInvocation methodInvocation, Throwable ex, Throwable mostSpecificCause) {
        StringBuffer message = new StringBuffer("Caught [(").append(ex.getClass()).append(") ");
        message.append(mostSpecificCause.getMessage()).append("]");
        message.append(" in ");
        message.append(buildInvocationMessage(methodInvocation));
        return message.toString();
    }

    protected String buildInvocationMessage(MethodInvocation methodInvocation) {
        StringBuffer message = new StringBuffer();
        message.append(methodInvocation.getMethod().getDeclaringClass());
        message.append("::").append(methodInvocation.getMethod().getName());
        message.append("(").append(getAsCSV(methodInvocation.getArguments())).append(")");
        return message.toString();
    }

    private Throwable getRootCause(Throwable t) {
        Throwable cause = t.getCause();
        return (cause == null) ? t : getRootCause(cause);
    }
    
    public static String getAsCSV(Object[] array) {
            StringBuffer csv = new StringBuffer();
            if (array != null) {
                    for (int i = 0; i < array.length; i++) {
                            csv.append(array[i]);
                            if (i + 1 < array.length) {
                                    csv.append(", ");
                            }
                    }
            }
            return csv.toString();
    }    
}
